package com.example.snow

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Color
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.MediaStore
import android.view.View
import android.view.WindowInsets
import android.view.WindowInsetsController
import android.view.WindowManager
import android.webkit.*
import android.widget.Button
import android.widget.LinearLayout
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import java.io.File
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.*

class MainActivity : AppCompatActivity() {

    private lateinit var webView: ScrollAwareWebView
    private lateinit var swipeRefreshLayout: SwipeRefreshLayout

    // 文件上传相关变量
    private var filePathCallback: ValueCallback<Array<Uri>>? = null
    private var cameraPhotoPath: String? = null

    // 权限请求
    private val requestPermissionLauncher = registerForActivityResult(
        ActivityResultContracts.RequestMultiplePermissions()
    ) { permissions ->
        val allGranted = permissions.values.all { it }
        if (allGranted) {
            // 权限已授予，加载网页
            loadWebPage()
        } else {
            // 权限被拒绝，显示提示
            showToast("部分权限被拒绝，某些功能可能无法使用")
            loadWebPage() // 仍然尝试加载网页，但文件上传可能不可用
        }
    }

    // 要加载的网页地址
    private val targetUrl = "http://192.168.1.212:8880/note/app/home"

    // 错误处理相关
    private var hasShownErrorPage = false
    private var lastErrorTime: Long = 0
    private val errorThreshold = 5000 // 5秒内不重复显示错误

    @SuppressLint("SetJavaScriptEnabled","ObsoleteSdkInt", "InlinedApi")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        try {
            // 在设置全屏之前，先设置输入法模式
            window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)


            // 设置全屏显示，必须在setContentView之前调用
            setFullScreen()

            setContentView(R.layout.activity_main)

            if (!initViews()) {
                showToast("视图初始化失败")
                finish()
                return
            }
            setupErrorHandling() // 添加错误处理设置
            setupWebView()
            checkPermissions()
        } catch (e: Exception) {
            e.printStackTrace()
            showToast("应用启动失败: ${e.message}")
            finish()
        }
    }

    /**
     * 设置完全全屏显示
     */
    @SuppressLint("ObsoleteSdkInt", "InlinedApi")
    private fun setFullScreen() {
        // 隐藏ActionBar
        supportActionBar?.hide()

        // 设置全屏标志，但保留输入法显示能力
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            window.insetsController?.let {
                // 隐藏状态栏
                it.hide(WindowInsets.Type.statusBars())
                // 隐藏导航栏
                it.hide(WindowInsets.Type.navigationBars())
                // 设置行为：滑动时临时显示系统栏
                it.systemBarsBehavior = WindowInsetsController.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
                // 确保不隐藏输入法
                it.show(WindowInsets.Type.ime())
            }
            window.setDecorFitsSystemWindows(false)
        } else {
            @Suppress("DEPRECATION")
            window.decorView.systemUiVisibility = (
                    View.SYSTEM_UI_FLAG_FULLSCREEN or
                            View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or
                            View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY or
                            View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or
                            View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or
                            View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    )
            @Suppress("DEPRECATION")
            window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN)
        }

        // 设置导航栏和状态栏颜色为透明
        window.navigationBarColor = Color.TRANSPARENT
        window.statusBarColor = Color.TRANSPARENT

        // 关键：确保窗口调整以适应输入法
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE or WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE)
    }

    // 当Activity重新获得焦点时，确保仍然全屏
    override fun onWindowFocusChanged(hasFocus: Boolean) {
        super.onWindowFocusChanged(hasFocus)
        if (hasFocus) {
            setFullScreen()
        }
    }

    // 当用户与屏幕交互时，保持全屏
    override fun onResume() {
        super.onResume()
        setFullScreen()
    }

    /**
     * 初始化视图组件
     */
    private fun initViews(): Boolean {
        return try {
            webView = findViewById(R.id.webView)
            swipeRefreshLayout = findViewById(R.id.swipeRefreshLayout)

            // 设置 WebView 和 SwipeRefreshLayout 的关联
            webView.setSwipeRefreshLayout(swipeRefreshLayout)

            // 设置WebView的内边距，避免内容被系统栏遮挡
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                // Android 11+ 使用 WindowInsets
                webView.setOnApplyWindowInsetsListener { view, insets ->
                    val systemBars = insets.getInsets(WindowInsets.Type.systemBars())
                    view.setPadding(0, 0, 0, systemBars.bottom)
                    insets
                }
            }

            // 设置下拉刷新监听器
            swipeRefreshLayout.setOnRefreshListener {
                hasShownErrorPage = false
                webView.reload()
            }

            // 设置下拉刷新的进度圈颜色
            swipeRefreshLayout.setColorSchemeResources(
                android.R.color.holo_blue_bright,
                android.R.color.holo_green_light,
                android.R.color.holo_orange_light,
                android.R.color.holo_red_light
            )

            true
        } catch (e: Exception) {
            e.printStackTrace()
            false
        }
    }

    /**
     * 配置 WebView 设置
     */
    @SuppressLint("SetJavaScriptEnabled")
    private fun setupWebView() {
        try {
            val webSettings = webView.settings

            // 启用 JavaScript
            webSettings.javaScriptEnabled = true

            // 启用 DOM 存储
            webSettings.domStorageEnabled = true

            // 启用数据库
            webSettings.databaseEnabled = true

            // 设置缓存策略
            webSettings.cacheMode = WebSettings.LOAD_DEFAULT

            // 启用缩放功能
            webSettings.setSupportZoom(true)
            webSettings.builtInZoomControls = true
            webSettings.displayZoomControls = false

            // 设置布局算法
            webSettings.layoutAlgorithm = WebSettings.LayoutAlgorithm.NORMAL
            webSettings.useWideViewPort = true
            webSettings.loadWithOverviewMode = true

            // 启用地理定位
            webSettings.setGeolocationEnabled(true)

            // 文件访问设置
            webSettings.allowFileAccess = true
            webSettings.allowContentAccess = true

            // 混合内容处理（Android 5.0+）
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                webSettings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
            }


            // 启用文本输入和表单输入
            webSettings.javaScriptCanOpenWindowsAutomatically = true
            webSettings.setSupportMultipleWindows(true)

            // 启用文本缩放（重要）
            webSettings.textZoom = 100

            // 启用内容编辑
            webSettings.loadsImagesAutomatically = true
            webSettings.blockNetworkImage = false
            webSettings.blockNetworkLoads = false

            // 设置布局参数，确保输入框可见
            webSettings.useWideViewPort = true
            webSettings.loadWithOverviewMode = true
            webSettings.setSupportZoom(true)
            webSettings.builtInZoomControls = true
            webSettings.displayZoomControls = false

            // 设置 WebView 的焦点相关属性
            webView.isFocusable = true
            webView.isFocusableInTouchMode = true
            webView.requestFocus()

            // 设置滚动条样式，避免遮挡输入框
            webView.scrollBarStyle = WebView.SCROLLBARS_OUTSIDE_OVERLAY
            webView.isScrollbarFadingEnabled = true



            // 设置 WebView 客户端
            webView.webViewClient = object : WebViewClient() {
                override fun onPageStarted(view: WebView?, url: String?, favicon: android.graphics.Bitmap?) {
                    super.onPageStarted(view, url, favicon)
                    // 页面开始加载时禁用下拉刷新
                    swipeRefreshLayout.isEnabled = false
                }

                override fun shouldOverrideUrlLoading(
                    view: WebView?,
                    request: WebResourceRequest?
                ): Boolean {
                    val url = request?.url.toString()
                    return handleSpecialLinks(url) || super.shouldOverrideUrlLoading(view, request)
                }

                @Deprecated("Deprecated in API 23")
                override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
                    return url?.let { handleSpecialLinks(it) } ?: false
                }

                override fun onPageFinished(view: WebView?, url: String?) {
                    super.onPageFinished(view, url)
                    swipeRefreshLayout.isRefreshing = false

                    // 页面加载完成后，根据滚动位置启用/禁用下拉刷新
                    runOnUiThread {
                        swipeRefreshLayout.isEnabled = webView.scrollY == 0
                    }

                    // 页面加载成功，隐藏错误布局
                    runOnUiThread {
                        hideErrorLayout()
                    }
                }

                override fun onReceivedError(
                    view: WebView?,
                    request: WebResourceRequest?,
                    error: WebResourceError?
                ) {
                    super.onReceivedError(view, request, error)

                    // 只处理主框架的错误，忽略子资源错误
                    if (request?.isForMainFrame == true) {
                        handleLoadError()
                    }
                }

                @Suppress("DEPRECATION")
                override fun onReceivedError(
                    view: WebView?,
                    errorCode: Int,
                    description: String?,
                    failingUrl: String?
                ) {
                    super.onReceivedError(view, errorCode, description, failingUrl)
                    // 只处理主框架错误
                    if (failingUrl == targetUrl || failingUrl == webView.url) {
                        handleLoadError()
                    }
                }
            }

            // 设置 WebChrome 客户端 - 禁用控制台错误显示
            webView.webChromeClient = object : WebChromeClient() {
                override fun onProgressChanged(view: WebView?, newProgress: Int) {
                    if (newProgress < 100) {
                        swipeRefreshLayout.isRefreshing = true
                    } else {
                        swipeRefreshLayout.isRefreshing = false
                    }
                }

                override fun onGeolocationPermissionsShowPrompt(
                    origin: String?,
                    callback: GeolocationPermissions.Callback?
                ) {
                    // 直接授权地理位置权限
                    callback?.invoke(origin, true, false)
                }

                // 处理文件选择
                override fun onShowFileChooser(
                    webView: WebView?,
                    filePathCallback: ValueCallback<Array<Uri>>?,
                    fileChooserParams: FileChooserParams?
                ): Boolean {
                    // 清除之前的回调
                    this@MainActivity.filePathCallback?.onReceiveValue(null)
                    this@MainActivity.filePathCallback = filePathCallback

                    return try {
                        createFileChooserIntent()
                        true
                    } catch (e: Exception) {
                        e.printStackTrace()
                        filePathCallback?.onReceiveValue(null)
                        false
                    }
                }

                // 重写控制台消息方法，过滤掉错误日志
                override fun onConsoleMessage(consoleMessage: ConsoleMessage?): Boolean {
                    // 只显示重要级别的日志，忽略错误和警告
                    consoleMessage?.let {
                        when (it.messageLevel()) {
                            ConsoleMessage.MessageLevel.LOG,
                            ConsoleMessage.MessageLevel.DEBUG,
                            ConsoleMessage.MessageLevel.TIP -> {
                                // 可选：在开发时显示这些日志
                                // Log.d("WebView", "${it.sourceId()}:${it.lineNumber()} ${it.message()}")
                            }
                            else -> {
                                // 忽略 ERROR、WARNING 级别的控制台消息
                            }
                        }
                    }
                    return true
                }

                // 添加以下方法确保输入法正常工作
                override fun onShowCustomView(view: View?, callback: CustomViewCallback?) {
                    super.onShowCustomView(view, callback)
                    // 处理全屏视频等情况，确保输入法不被影响
                }

                override fun onHideCustomView() {
                    super.onHideCustomView()
                    // 退出全屏模式时恢复输入法设置
                }

            }

            // 添加 JavaScript 接口
            webView.addJavascriptInterface(WebAppInterface(this), "AndroidApp")

        } catch (e: Exception) {
            e.printStackTrace()
            // 加载一个简单的错误页面
            loadLocalPage()
        }
    }

    /**
     * 创建文件选择器 Intent
     */
    private fun createFileChooserIntent() {
        try {
            val contentSelectionIntent = Intent(Intent.ACTION_GET_CONTENT).apply {
                addCategory(Intent.CATEGORY_OPENABLE)
                type = "*/*"
                putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true)
            }

            val cameraIntents = mutableListOf<Intent>()

            // 检查相机权限和可用性
            if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
                val takePictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
                if (takePictureIntent.resolveActivity(packageManager) != null) {
                    val photoFile = try {
                        createImageFile()
                    } catch (e: IOException) {
                        e.printStackTrace()
                        null
                    }
                    photoFile?.let {
                        val photoURI = FileProvider.getUriForFile(
                            this,
                            "${packageName}.provider",
                            it
                        )
                        takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI)
                        takePictureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
                        cameraIntents.add(takePictureIntent)
                    }
                }
            }

            val chooserIntent = Intent(Intent.ACTION_CHOOSER).apply {
                putExtra(Intent.EXTRA_INTENT, contentSelectionIntent)
                putExtra(Intent.EXTRA_TITLE, "选择文件或拍照")
                if (cameraIntents.isNotEmpty()) {
                    putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toTypedArray())
                }
            }

            fileChooserLauncher.launch(chooserIntent)
        } catch (e: Exception) {
            e.printStackTrace()
            filePathCallback?.onReceiveValue(null)
            filePathCallback = null
        }
    }

    // 文件选择结果处理
    private val fileChooserLauncher = registerForActivityResult(
        ActivityResultContracts.StartActivityForResult()
    ) { result ->
        try {
            if (result.resultCode == Activity.RESULT_OK) {
                val data: Intent? = result.data
                handleFileChooserResult(data)
            } else {
                filePathCallback?.onReceiveValue(null)
            }
        } catch (e: Exception) {
            e.printStackTrace()
            filePathCallback?.onReceiveValue(null)
        } finally {
            filePathCallback = null
            cameraPhotoPath = null
        }
    }

    /**
     * 处理文件选择结果
     */
    private fun handleFileChooserResult(data: Intent?) {
        try {
            val results = when {
                data?.clipData != null -> {
                    val count = data.clipData!!.itemCount
                    Array(count) { i ->
                        data.clipData!!.getItemAt(i).uri
                    }
                }
                data?.data != null -> {
                    arrayOf(data.data!!)
                }
                cameraPhotoPath != null -> {
                    val file = File(cameraPhotoPath!!.removePrefix("file://"))
                    if (file.exists()) {
                        arrayOf(FileProvider.getUriForFile(
                            this,
                            "${packageName}.provider",
                            file
                        ))
                    } else {
                        null
                    }
                }
                else -> null
            }
            filePathCallback?.onReceiveValue(results)
        } catch (e: Exception) {
            e.printStackTrace()
            filePathCallback?.onReceiveValue(null)
        }
    }

    /**
     * 检查并请求权限
     */
    private fun checkPermissions() {
        val permissions = mutableListOf<String>()

        // 添加存储权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            // Android 13+ 使用新的媒体权限
            if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_MEDIA_IMAGES) != PackageManager.PERMISSION_GRANTED) {
                permissions.add(android.Manifest.permission.READ_MEDIA_IMAGES)
            }
        } else {
            // Android 12 及以下使用传统存储权限
            if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                permissions.add(android.Manifest.permission.READ_EXTERNAL_STORAGE)
            }
        }

        // 添加相机权限
        if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            permissions.add(android.Manifest.permission.CAMERA)
        }

        if (permissions.isNotEmpty()) {
            requestPermissionLauncher.launch(permissions.toTypedArray())
        } else {
            loadWebPage()
        }
    }

    /**
     * 创建临时图片文件
     */
    @Throws(IOException::class)
    private fun createImageFile(): File? {
        val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date())
        val imageFileName = "JPEG_${timeStamp}_"
        val storageDir = getExternalFilesDir(null)

        return File.createTempFile(
            imageFileName,
            ".jpg",
            storageDir
        ).apply {
            cameraPhotoPath = "file://$absolutePath"
        }
    }

    /**
     * 加载网页
     */
    private fun loadWebPage() {
        try {
            if (targetUrl.isNotEmpty()) {
                webView.loadUrl(targetUrl)
            } else {
                loadLocalPage()
            }
        } catch (e: Exception) {
            e.printStackTrace()
            loadLocalPage()
        }
    }

    /**
     * 处理特殊链接（电话、邮件等）
     */
    private fun handleSpecialLinks(url: String): Boolean {
        return try {
            when {
                url.startsWith("tel:") -> {
                    val intent = Intent(Intent.ACTION_DIAL, Uri.parse(url))
                    startActivity(intent)
                    true
                }
                url.startsWith("mailto:") -> {
                    val intent = Intent(Intent.ACTION_SENDTO, Uri.parse(url))
                    startActivity(intent)
                    true
                }
                url.startsWith("geo:") -> {
                    val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
                    startActivity(intent)
                    true
                }
                url.startsWith("whatsapp:") -> {
                    try {
                        val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
                        startActivity(intent)
                    } catch (e: Exception) {
                        // 静默失败，不显示提示
                    }
                    true
                }
                url.startsWith("http") -> {
                    // 允许加载所有 http/https 链接
                    false
                }
                else -> {
                    // 其他链接尝试用外部浏览器打开
                    try {
                        val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
                        startActivity(intent)
                        true
                    } catch (e: Exception) {
                        false
                    }
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
            false
        }
    }

    private fun loadLocalPage() {
        webView.loadData(
            """
            <!DOCTYPE html>
            <html>
            <head>
                <meta charset="utf-8">
                <meta name="viewport" content="width=device-width, initial-scale=1">
                <style>
                    body { 
                        font-family: Arial, sans-serif; 
                        margin: 40px; 
                        text-align: center; 
                        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                        color: white;
                        height: 100vh;
                        display: flex;
                        flex-direction: column;
                        justify-content: center;
                        align-items: center;
                    }
                    .container { 
                        background: rgba(255,255,255,0.1); 
                        padding: 30px; 
                        border-radius: 15px; 
                        backdrop-filter: blur(10px);
                    }
                    h1 { margin-bottom: 20px; }
                    .error { color: #ff6b6b; margin-top: 20px; }
                </style>
            </head>
            <body>
                <div class="container">
                    <h1>📱 应用已启动</h1>
                    <p>WebView 运行正常</p>
                    <p>目标网址: $targetUrl</p>
                    <div class="error">
                        <p>如果长时间无法加载，请检查：</p>
                        <p>• 网络连接</p>
                        <p>• 服务器状态</p>
                        <p>• 网址是否正确</p>
                    </div>
                    <button onclick="window.location.reload()" style="margin-top: 20px; padding: 10px 20px; background: white; color: #667eea; border: none; border-radius: 5px; cursor: pointer;">重新加载</button>
                </div>
            </body>
            </html>
            """.trimIndent(),
            "text/html",
            "UTF-8"
        )
    }

    private fun showToast(message: String) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
    }

    override fun onBackPressed() {
        if (webView.canGoBack()) {
            webView.goBack()
        } else {
            super.onBackPressed()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        // 清理 WebView 资源
        webView.stopLoading()
        webView.webViewClient = WebViewClient()
        webView.webChromeClient = WebChromeClient()
        webView.destroy()
    }

    // 在 MainActivity 中添加以下方法来处理错误布局和重试按钮
    private fun setupErrorHandling() {
        val errorLayout = findViewById<LinearLayout>(R.id.errorLayout)
        val btnRetry = findViewById<Button>(R.id.btnRetry)

        btnRetry.setOnClickListener {
            errorLayout.visibility = View.GONE
            webView.visibility = View.VISIBLE
            hasShownErrorPage = false
            // 重试时启用下拉刷新
            swipeRefreshLayout.isEnabled = true
            loadWebPage()
        }
    }

    /**
     * 隐藏错误布局
     */
    private fun hideErrorLayout() {
        runOnUiThread {
            val errorLayout = findViewById<LinearLayout>(R.id.errorLayout)
            val webView = findViewById<ScrollAwareWebView>(R.id.webView)

            errorLayout.visibility = View.GONE
            webView.visibility = View.VISIBLE
        }
    }

    /**
     * 处理加载错误
     */
    private fun handleLoadError() {
        val currentTime = System.currentTimeMillis()

        // 防止频繁显示错误页面
        if (hasShownErrorPage && (currentTime - lastErrorTime) < errorThreshold) {
            return
        }

        swipeRefreshLayout.isRefreshing = false
        // 发生错误时禁用下拉刷新
        swipeRefreshLayout.isEnabled = false
        hasShownErrorPage = true
        lastErrorTime = currentTime

        // 延迟显示错误布局，给页面重试的机会
        webView.postDelayed({
            // 再次检查页面是否已经加载成功
            if (!webView.url.isNullOrEmpty() && webView.progress == 100) {
                return@postDelayed
            }

            // 显示错误布局
            runOnUiThread {
                val errorLayout = findViewById<LinearLayout>(R.id.errorLayout)
                val webView = findViewById<ScrollAwareWebView>(R.id.webView)

                errorLayout.visibility = View.VISIBLE
                webView.visibility = View.GONE
            }
        }, 2000) // 延迟2秒显示错误
    }

    // JavaScript 接口类
    class WebAppInterface(private val context: MainActivity) {
        @JavascriptInterface
        fun showToast(message: String) {
            Toast.makeText(context, message, Toast.LENGTH_SHORT).show()
        }

        @JavascriptInterface
        fun getDeviceInfo(): String {
            return "Android ${Build.VERSION.RELEASE} - ${Build.MANUFACTURER} ${Build.MODEL}"
        }

        @JavascriptInterface
        fun closeApp() {
            context.finish()
        }

        @JavascriptInterface
        fun getAppVersion(): String {
            return try {
                val packageInfo = context.packageManager.getPackageInfo(context.packageName, 0)
                packageInfo.versionName ?: "1.0.0"
            } catch (e: Exception) {
                "1.0.0"
            }
        }
    }
}